import Vue from 'vue'
import VueRouter from 'vue-router'
import jwtdecode from "jwt-decode"

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    name: 'login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/regist',
    name: 'regist',
    component: () => import('../views/Regist.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/Home.vue'),
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('../views/Welcome'),
      },
      {
        path: '/fundlist',
        name: 'fundlist',
        component: () => import('../views/Fundlist'),
      }, {
        path: '/info',
        name: 'info',
        component: () => import('../views/Info'),
      }
    ]

  }
]

const router = new VueRouter({
  routes
})

router.afterEach((to,from,next) => {

  //查看token看是否有token有直接放行没有再返回登录页面
  let token = localStorage.getItem('token')
  // 把token从新赋值一下 
  let result = jwtdecode(token)
  console.log(result);
  let nowtiem = parseInt(new Date().getTime()/1000)
  //登录和注册直接放行
  if (to.path == '/login' || to.path == '/regist') {
    next();
  }

  if (token) {
    if (nowtiem - result.exp>0) {
      next("/login")
    } else {
      next()
    }
  }
})

export default router
